package middle;

import java.util.Stack;

public class Solution_230 {

    public static void main(String[] args) {
        Solution_230 model = new Solution_230();
//        TreeNode root = new TreeNode(3);
//        root.left = new TreeNode(1);
//        root.left.right = new TreeNode(2);
//        root.right = new TreeNode(4);

        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(2);
        root.left.left.left = new TreeNode(1);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(6);
        System.out.println(model.kthSmallest(root, 3));
    }

    public int kthSmallest(TreeNode root, int k) {
        TreeNode node = root;
        Stack<TreeNode> stack = new Stack<>();
        int count = 0;
        while (!stack.empty() || node != null) {
            if (node == null) {
                TreeNode pop = stack.pop();
//                System.out.println(pop.val);
                count++;
                if (count == k) {
                    return pop.val;
                }
                node = pop.right;
            } else {
                stack.push(node);
                node = node.left;
            }
        }
        return 0;
    }

    static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
}
